package db

import (
	"database/sql"
	"logs"

	_ "github.com/lib/pq"
)

var db *sql.DB = nil
var err error

const (
	dbport   = "5432"
	dbuser   = "postgres"
	password = "123456"
	dbname   = "postgres"
	sslmode  = "disable"
)

func Opendb() error {
	var err error = nil
	if db == nil {
		sqlopen := "port=" + dbport + " user=" + dbuser + " password=" + password + " dbname=" + dbname + " sslmode=" + sslmode
		db, err = sql.Open("postgres", sqlopen)
		if err != nil {
			logs.Print("sql.Open failed :", err.Error())
		}
	}
	return err
}

func Getdb() (*sql.DB, error) {
	var err error = nil
	if db == nil {
		err = Opendb()
		if err != nil {
			logs.Print("Getdb failed :", err.Error())
		}
	}
	return db, err
}

func Closedb(db *sql.DB) error {
	err := db.Close()
	if err != nil {
		logs.Print("closrdb failed :", err.Error())
	} else {
		logs.Print("closedb success")
	}
	return err
}

func RowQuery(Sql string, args ...interface{}) (*sql.Rows, error) {
	stmt, err := db.Prepare(Sql)
	defer stmt.Close()
	if err != nil {
		logs.Print("rowQuery db.Prepare error:", err.Error())
		return nil, err
	}
	rows, err := stmt.Query(args...)
	if err != nil {
		logs.Print("rowQuery db.Query error:", err.Error())
		return nil, err
	}
	return rows, err
}

func TxQuery(tx *sql.Tx, Sql string, args ...interface{}) (*sql.Stmt, *sql.Rows, error) {
	stmt, err := tx.Prepare(Sql)
	if err != nil {
		logs.Print("txQuery tx.Prepare error:", err.Error())
		return nil, nil, err
	}
	rows, err := stmt.Query(args...)
	if err != nil {
		logs.Print("txQuery stmt.Query error:", err.Error())
		return nil, nil, err
	}
	return stmt, rows, err
}

func TxExec(tx *sql.Tx, Sql string, args ...interface{}) error {
	stmt, err := tx.Prepare(Sql)
	defer stmt.Close()
	if err != nil {
		logs.Print("txExec tx.Prepare error:", err.Error())
		return err
	}
	_, err = stmt.Exec(args...)
	if err != nil {
		logs.Print("txExec tx.Exec error:", err.Error())
		return err
	}
	return err
}
